package emby.stmt;

import emby.EmbyRuntime;
import emby.expr.Variable;
import emby.lang.Block;
import emby.lang.Scope;
import emby.lang.ThrownObject;
import emby.writer.IEmbyCodifier;

public class TryCatch extends Statement{

	private static final long serialVersionUID = -1612306217491626043L;
	private Block tryBlock;
	private Variable exceptionVariable;
	private Block catchBlock;

	public TryCatch(Block tryBlock, Variable eVar, Block catchBlock){
		this.tryBlock=tryBlock;
		this.exceptionVariable= eVar;
		this.catchBlock=catchBlock;
	}

	@Override
	public Object eval(Scope s) {
		if(EmbyRuntime.echo){
			emby.util.Print.println("Evaluating try_catch statement.");
		}
		Object returnVal = null;
		try{
			returnVal  = tryBlock.eval(s);

		}catch(ThrownObject obj){
			s.setVar(exceptionVariable.getName(), obj.getObj());
			returnVal  = catchBlock.eval(s);
		}catch(Throwable e){
			s.setVar(exceptionVariable.getName(), e);
			 returnVal  = catchBlock.eval(s);
		}finally{
			if(returnVal!=null){
				return returnVal;
			}
		}
		// TODO Auto-generated method stub
		return null;
	}

	public void codify(IEmbyCodifier ec){
		ec.trycatch(tryBlock, exceptionVariable, catchBlock);
	}
}
